package cn.diancan.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.diancan.dao.MyBaseDao;
import cn.diancan.exception.OutMsgException;
import cn.diancan.model.Color;
import cn.diancan.model.Specification;
import cn.diancan.model.SpecificationValue;
import cn.diancan.model.types.CommonType;
import cn.diancan.service.ColorService;
import cn.diancan.service.SpecificationService;
import cn.diancan.util.DateUtil;
import cn.diancan.util.SortChineseText;
import cn.diancan.vo.other.Pager;

@Component("specificationService")
public class SpecificationServiceImpl implements SpecificationService{
    
 
    
    @Resource(name="MyBaseDao")
    private MyBaseDao<Specification> specificationDao;
    
    @Resource(name="MyBaseDao")
    private MyBaseDao<SpecificationValue> specificationValueDao;
    
    @Resource(name="colorService")
    private ColorService colorService;
    
    
    @Override
    public Specification saveSpecification(String specificationName,String[] spValue) throws OutMsgException,Exception{
	if(null==specificationName || "".equals(specificationName.trim()) ){
	    throw new OutMsgException("规格名称不可为空");
	}
	if(null==spValue || spValue.length<=0){
	    throw new OutMsgException("规格值不可为空");
	}
	specificationName=specificationName.trim();
	String createTime =DateUtil.currentDateTime();
	Specification specification =findSpecificationByName(specificationName);
	if(null==specification){
	    	specification =new Specification(); 
		specification.setIsDelete(CommonType.Delete.NO);
		specification.setName(specificationName); 
		specification.setCreateTime(createTime);
		specification.setModifyTime(createTime);
		specification.setOrderNo(1);
		specification.setMemo("");
		specificationDao.save(specification);
	}
	
	
	String valueStr=specification.getValueStr();
	List<String> spValueList =handleSpecificationValues(spValue, 0);
	
	
	List<SpecificationValue> specificationValueList = new ArrayList<SpecificationValue>();
	for (int i =0; i < spValueList.size() ; i++) { 
	    String temValue=spValueList.get(i);  
	    valueStr+=temValue+" ";
	    SpecificationValue specificationValue = findSpecificationValueByValue(specification.getId(), temValue);
	    if(null!=specificationValue){
		continue;
	    }
	    specificationValue = new SpecificationValue();
	    specificationValue.setCreateTime(createTime);
	    specificationValue.setIsDelete(CommonType.Delete.NO); 
	    specificationValue.setOrderNo(i+1);
	    specificationValue.setSpecification(specification);
	    specificationValue.setValue(temValue);
	    
	    
	    //colorService.
	    if("颜色".equals(specificationName)){
				Color color = colorService.findColorByColorName(temValue);
				if(null!=color){
					specificationValue.setValueKey(color.getColorNumber());
				}
	    }else{
			specificationValue.setValueKey(""+(i+1));
	    }
	    
	    specificationValueDao.save(specificationValue);
	   //specificationValueList.add(specificationValue);
	}
	if(spValueList.size()<=0){
	    throw new OutMsgException("没有有效的规格值");
	}
	
	specification.setValueStr(valueStr.trim());
	specification.setValueSize(spValueList.size());
	
	
	return specification;
    } 
    
   //-1 倒序  0 不排序 1 正序
    private List<String> handleSpecificationValues(String[] spValue ,int sortType){
	//去重复   去掉空格 
	List<String> spValueList = new ArrayList<String>();
	for(int i=0;i<spValue.length;i++){
	    String spTmpValue = spValue[i];
	    if(null!=spTmpValue&& !"".equals(spTmpValue.trim())){
		if(Collections.frequency(spValueList,spTmpValue.trim()) <1){
		    spValueList.add(spTmpValue.trim());
		}
	    }
	}
	
	//去重复
	//Set<String> set = new HashSet<String>(Arrays.asList(spValue));
	//spValue=set.toArray(new String[]{});
	//List<String> spValueList = Arrays.asList(spValue);
	
	//去掉空格 
	/*for (int i = spValueList.size()-1; i >=0 ; i--) { 
	    String temValue=spValueList.get(i);
	    if(null==temValue || "".equals(temValue.trim())){
		spValueList.remove(i);
		continue;
	    }
	} */
	
	switch (sortType) {
	case 1://正序
	    Collections.sort(spValueList, new SortChineseText()); 
	    break;  
	default:
	    break;
	}
	return spValueList;
    }
    
    @Override
    public Pager findPagerBySpecification(Pager pager,String keyWords)   throws OutMsgException {
	String hql = "FROM Specification WHERE isDelete=? ";
	List<Object> param =new ArrayList<Object>();
	param.add(CommonType.Delete.NO);
	if(null!= keyWords && !"".equals(keyWords.trim())){
	    hql+=" AND (instr(name,?)>0 OR instr(valueStr,?)>0 )";
	    param.add(keyWords.trim());
	    param.add(keyWords.trim());
	}
	
	List<Specification> specifications = specificationDao.find(hql, param,pager.getPageNumber(),pager.getPageSize());
	Long count = specificationDao.count("SELECT count(id) "+hql, param);
	pager.setList(specifications);
	pager.setTotalCount(count.intValue());
	
	return  pager;
    } 
 
    @Override
    public boolean updatePlusSpecification(Long specificationId,String specificationName, String[] spValue)	    throws OutMsgException {
	if(null==specificationId){
	    throw new OutMsgException("");
	}
	if(null==specificationName || "".equals(specificationName.trim()) ){
	    throw new OutMsgException("规格名称不可为空");
	}
	
	specificationName =specificationName.trim();

	
	Specification specification =findSpecificationByName(specificationName);
	if(null!=specification  && !specificationId.equals(specification.getId())){ 
	    throw new OutMsgException("该规格名称已被使用");
	} 
	specification=findSpecificationById(specificationId);
	if(null==specification){
	    throw new OutMsgException("该规格不存在");
	}

	String createTime = DateUtil.currentDateTime();
	specification.setModifyTime(createTime);
	specification.setName(specificationName);
	
	if(null!=spValue && spValue.length>0){
		List<String> spValueList =handleSpecificationValues(spValue, 0);
		//
		
		String valueStr=specification.getValueStr()+" ";
		Integer  orderNo = specification.getValueSize();//当成最大的OrderNo
		List<SpecificationValue> specificationValueList = new ArrayList<SpecificationValue>();
		for (int i =0; i < spValueList.size() ; i++) {  
		    String temValue=spValueList.get(i);
		    SpecificationValue specificationValue =   specificationValueDao.get("FROM SpecificationValue WHERE specificationId=? AND value=? AND isDelete=?", new Object[]{specification.getId(),temValue,CommonType.Delete.NO});
		    if(null!=specificationValue){
			spValueList.remove(i);
			i--;
			continue;
		    }
		    
		    valueStr+=temValue+" ";
		    specificationValue =new SpecificationValue();
		    specificationValue.setCreateTime(createTime);
		    specificationValue.setIsDelete(CommonType.Delete.NO); 
		    specificationValue.setOrderNo(orderNo+i+1);
		    specificationValue.setSpecification(specification);
		    specificationValue.setValue(temValue);
		    specificationValue.setValueKey("");
		    specificationValueDao.save(specificationValue);
		    specificationValueList.add(specificationValue);
		}
		if(spValueList.size()<=0){
		    throw new OutMsgException("没有有效的规格值");
		}
		specification.setValueStr(valueStr.trim());
		specification.setValueSize(specification.getValueSize()+spValueList.size());
	}
	
	specificationDao.update(specification);
	return true;
    } 
    
    
    @Override
    public Specification findSpecificationById(Long specificationById)	    throws OutMsgException {
	if(null== specificationById){
	    throw new OutMsgException("参数错误");
	}
	return specificationDao.get("FROM Specification WHERE id=? AND isDelete=?", new Object[]{specificationById,CommonType.Delete.NO});
    }  
    

    @Override
    public Specification findSpecificationByName(String specificationName)  throws OutMsgException {
	if(null==specificationName || "".equals(specificationName.trim()) ){
	    throw new OutMsgException("规格名称不可为空");
	}
	specificationName =specificationName.trim();
	return specificationDao.get("FROM Specification WHERE name=? AND isDelete=?", new Object[]{specificationName,CommonType.Delete.NO});
    }

    
    @Override
    public SpecificationValue findSpecificationValueByValue(Long specificationId, String specificationValue) throws OutMsgException{
	if(null==specificationId){
	    throw new OutMsgException("请选择规格");
	}
	if(null==specificationValue || "".equals(specificationValue.trim()) ){
	    throw new OutMsgException("规格值不可为空");
	}
	specificationValue =specificationValue.trim();
	return specificationValueDao.get("FROM SpecificationValue WHERE isDelete=? AND specificationId=? AND value=?", new Object[]{CommonType.Delete.NO,specificationId,specificationValue});
    }

    
    @Override
    public SpecificationValue findSpecificationValueByValueKey(	    Long specificationId, String specificationValueKey)	    throws OutMsgException {
	if(null==specificationId){
	    throw new OutMsgException("请选择规格");
	}
	if(null==specificationValueKey || "".equals(specificationValueKey.trim()) ){
	    throw new OutMsgException("规格键值不可为空");
	}
	specificationValueKey =specificationValueKey.trim();
	return specificationValueDao.get("FROM SpecificationValue WHERE isDelete=? AND specificationId=? AND valueKey=?", new Object[]{CommonType.Delete.NO,specificationId,specificationValueKey});

    }

    @Override
    public SpecificationValue findSpecificationValueByNameAndValue(String name,  String value) throws OutMsgException {
	Specification specification = findSpecificationByName( name);
	 if(null== specification ){
	     throw new OutMsgException("规格不存在");
	 } 
	 SpecificationValue specificationValue=  findSpecificationValueByValue(specification.getId(),value  ); 
	return specificationValue;
    }

    @Override
    public List<SpecificationValue> findSpecificationValue( String name, String valueKeyWords)throws OutMsgException {
	 Specification specification = findSpecificationByName( name);
	 if(null== specification ){
	     throw new OutMsgException("规格不存在");
	 } 
	 
	 String hql ="FROM SpecificationValue WHERE isDelete=? AND specificationId=? ";
	 List<Object> param = new ArrayList<Object>();
	 param.add(CommonType.Delete.NO);
	 param.add(specification.getId());
	 if(null!=valueKeyWords){
	     hql+=" AND INSTR(value,?)>0 ";
	     param.add(valueKeyWords);
	 }
	 
	List<SpecificationValue> list= specificationValueDao.find(hql, param);
	return list;
    }
    
    @Override
    public List<Specification> findSizeSpecificationList()throws OutMsgException { 
	List<Specification> list = specificationDao.find("FROM Specification WHERE id>=? AND id<=?", new Object[]{141935l,141943l});
	return list;
    }

    @Override
    public SpecificationValue findSpecificationValueId(Long specificationId, Long specificationValueId)throws OutMsgException  {
	if(null == specificationId || null==specificationValueId){
	    throw new OutMsgException("参数错误");
	}
	SpecificationValue specificationValue =specificationValueDao.get("FROM SpecificationValue WHERE specificationId=? AND id=?", new Object[]{specificationId,specificationValueId}); 
	
	return specificationValue;
    }
    
    

}
